package org.hardcode.rpc.serialization.jdk;

import org.hardcode.rpc.common.exception.SerializerException;
import org.hardcode.rpc.serialization.api.Serialization;

import java.io.*;

/**
 * 基于jdk实现序列化和反序列化
 */
public class JdkSerialization implements Serialization {

    /**
     * 序列化
     *
     * @param object
     * @param <T>
     * @return
     */
    @Override
    public <T> byte[] serialize(T object) {
        if (object == null) {
            throw new SerializerException("serialize  object  is null");
        }
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();

            ObjectOutputStream out = new ObjectOutputStream(os);
            out.writeObject(object);
            return os.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 反序列化
     *
     * @param data
     * @param clazz
     * @param <T>
     * @return
     */
    @Override
    public <T> T deserialize(byte[] data, Class<T> clazz) {
        if (data == null) {
            throw new SerializerException("deserialize  data is null");
        }
        try {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);

            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);

            return  (T)objectInputStream.readObject();
        } catch (Exception e) {
            throw new SerializerException(e.getMessage(),e);
        }

    }
}
